<!--
 * @Author: fcli
 * @Date: 2023-09-04 10:34:58
 * @LastEditors: fcli
 * @LastEditTime: 2023-12-21 14:29:49
 * @FilePath: /vue-drag/src/plugin/index.vue
 * @Description: 拖拽组件
-->

<template>
    <div class="drag-content" :style="dragStyle" @mousedown="startTouch" @touchstart="startTouch"
        @touchend="endTouch" @mouseup="endTouch" @touchmove="moveTouch">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps({
    right: {
        type: String,
        default: "20px"
    },
    bottom: {
        type: String,
        default: "30px"
    }
})

//拖动样式
const dragStyle = ref({
    right: props.right,
    bottom: props.bottom,
    transform: 'translate(0,0)'
})
let isDragging = false;
let dragInfo = {
    offsetX: 0,
    offsetY: 0,
    endX: 0,
    endY: 0
}

//拖拽开始
const startTouch = (e: any) => {
    dragInfo.offsetX = (e.pageX || e.touches[0].pageX) - dragInfo.endX;
    dragInfo.offsetY = (e.pageY || e.touches[0].pageY) - dragInfo.endY;
    isDragging = true;
}

//适配pc端鼠标移动事件卡顿问题
document.onmousemove =  (e)=> {
    if (isDragging) {
        let offsetX = e.pageX - dragInfo.offsetX;
        let offsetY = e.pageY - dragInfo.offsetY;
        dragInfo.endX = offsetX;
        dragInfo.endY = offsetY;
        dragStyle.value.transform = `translate(${offsetX}px,${offsetY}px)`
    }
}

//拖动中，动态改变
const moveTouch = (e: any) => {
    if (isDragging) {
        //h5 touch事件
        let offsetX = e.touches[0].pageX - dragInfo.offsetX;
        let offsetY = e.touches[0].pageY - dragInfo.offsetY;

        //保存最新便宜量
        dragInfo.endX = offsetX;
        dragInfo.endY = offsetY;
        dragStyle.value.transform = `translate(${offsetX}px,${offsetY}px)`
    }
}

//结束拖动
const endTouch = () => {
    isDragging = false;
}

</script>
<style>
.drag-content {
    user-select: none;
    touch-action: none;
    cursor: pointer;
    position: fixed;
}
.circle{
    animation: test ease-in-out 1s infinite;

}
@keyframes test {
    0%{
        transform: scale(1);
    }

    50%{
        transform: scale(0.8);
    }

    100%{
        transform: scale(1);
    }
}
</style>
